Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: api_userlog.browser_info_id (when i want to add show me this error but update and list are working fine)
model.py from django.db import models from django.utils import timezone Create your models here. class PageOnHold(models.Model): timestamp = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) spent_time = models.IntegerField(max_length=None,blank=True, null=True) elapsed_time = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) class MouseClick(models.Model): timestamp = models.DateTimeField(blank=True, null=True,default=timezone.now) x_cord = models.IntegerField(max_length=None,blank=True, null=True) y_cord = models.IntegerField(max_length=None,blank=True, null=True) class MouseOver(models.Model): timestamp = models.DateTimeField(blank=True, null=True,default=timezone.now) x_cord = models.IntegerField(max_length=None,blank=True, null=True) y_cord = models.IntegerField(max_length=None,blank=True, null=True) class InteractionInfo(models.Model): page_in_time = models.DateTimeField(blank=True, null=True,default=timezone.now) page_on_hold = models.ForeignKey('PageOnHold',on_delete=models.CASCADE) page_out_time = models.DateTimeField(blank=True, null=True,default=timezone.now) estimated_time_spent = models.DateTimeField(max_length=None,blank=True, null=True,default=timezone.now) mouse_click = models.ForeignKey('MouseClick',on_delete= models.CASCADE) mouse_over = models.ForeignKey('MouseOver',on_delete= models.CASCADE) class NetworkInfo(models.Model): city = models.CharField(max_length=100) country = models.CharField(max_length=100) hostname = models.CharField(max_length=100) latitude = models.IntegerField(max_length=None) longitude = models.IntegerField(max_length=None) org = models.CharField(max_length=100) postal = models.IntegerField(max_length=None) region = models.CharField(max_length=100) timezone = models.DateTimeField(max_length=100,default=timezone.now) def __str__(self): return self.city class BrowserInfo(models.Model): app_code = models.CharField(max_length=100) app_name = models.CharField(max_length=100) app_version = models.CharField(max_length=100) cookie_enabled = models.BooleanField(default=False) language = models.CharField(max_length=100) online = models.BooleanField(default=False) platform = models.CharField(max_length=100) # plugins = models.ForeignKey(plugins) # another table should be implement user_agent = models.CharField(max_length=100) has_err = models.BooleanField(default=False) def __str__(self): return self.app_code class GeoLocation(models.Model): timestamp = models.DateTimeField(null=True,blank=True,default=timezone.now) coords = models.ForeignKey('Coords',on_delete=models.CASCADE) hasErr = models.BooleanField(default=False) errCode = models.CharField(max_length=100) def __str__(self): return self.errCode class Coords(models.Model): accuracy = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') altitude = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') altitudeAccuracy= models.CharField(max_length=100,blank=True, null=True,default='SOME STRING') heading = models.CharField(max_length=100,blank=True, null=True,default='SOME STRING') latitude = models.IntegerField(max_length=None,blank=True, null=True,default='SOME STRING') … -
Modify datetime value in result of F() expression
I am trying to modify datetime value while making filter. I need to make each scheduled_for value to 02:00 AM next day and compare this date to other field. So at first I add 1 day with timedelta(days=1) and then in annotation I try to replace hours and minutes: bookings = Booking.objects.filter( cancel_time__isnull=False ).annotate( invoice_date=ExpressionWrapper((F('scheduled_for') + timedelta(days=1)), output_field=models.DateTimeField()) ).annotate( invoice_time=F('invoice_date').replace(hour=2, minute=0, second=0, microsecond=0) ).filter(invoice_time__gte=F('cancel_time')) But that thing doesn't work and I got error: AttributeError: 'F' object has no attribute 'replace' Is there any way to accomplish what I am trying to do? P.S.: Also I am not sure should I use DurationField or DateTimeField as output_field in ExpressionWrapper. -
Unable to delete the data from mysql table which is fetched from a form in HTML using Django
I am want to: 1. save data from a HTML form to MySQL 2. delete data from mySQL which is entered through HTML form. The save functionality is working. While there is error in delete functionality. Model.py from django.db import models # Create your models here. class info_needed(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) surname = models.CharField(max_length=200) email = models.CharField(max_length=200) def __str__(self): return self.name views.py # Create your views here. from django.shortcuts import render from django.http import HttpResponse from .models import info_needed def index(request): return render(request,'userdata/index.html') def message(request): if request.method == 'POST': fname = request.POST.get("fname") lname = request.POST.get("lname") mail = request.POST.get("mail") action = request.POST.get("submit_button") action1 = request.POST.get("delete_button") p = info_needed(name = fname , surname = lname, email = mail) print("name", fname) print("action", action) print("action2", action1) if action == "Submit": p.save() elif action1 == "Delete": p.delete() else: return HttpResponse("Wrong Action Provided") return(HttpResponse("Thank you for submitting your details")) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name = 'index'), path('submit/', views.message, name = 'submit'), ] index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Page</title> </head> <body> <form action="{% url 'submit' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <label for="fname">Name:</label> <input type="text" id="fname" name="fname"><br><br> <label … -
New message notifications for contacts in django channel?
I'm working to build a real-time chat app with django channels like whatsapp. Its working and I can send/receive message to active chat contact. But the main problem is how to raise notification when new message come from other contacts? consumer.py class TwilioWChatConsumer(AsyncConsumer): async def websocket_connect(self, event): other_user = self.scope['url_route']['kwargs']['contect_id'] me = self.scope['user'] self.login_contact = await self.get_contact_by_user(me) if me.is_authenticated: if me.id == other_user: await self.send({ "type": "websocket.close", }) return False self.thread_obj = await self.get_thread(me, other_user) self.chat_room = f"ChatThread_{self.thread_obj.id}" await self.channel_layer.group_add( self.chat_room, self.channel_name ) await self.send({ "type": "websocket.accept", }) else: await self.send({ "type": "websocket.close", }) async def websocket_receive(self, event): user = self.scope['user'] other_contect_id = self.scope['url_route']['kwargs']['contect_id'] if user.is_authenticated: text = json.loads(event['text']) if type(event['text']) == str else event['text'] other_contact = await self.get_contact(event['from_contect']) chatMsg = await self.create_chat_message(other_contact, text['Body']) myResponse = { 'message': event['text']['Body'], 'contact_type': 'asker', 'timestamp': str(chatMsg.timestamp.strftime("%d %b %y, %H:%M:%S")), } await self.channel_layer.group_send( self.chat_room, { 'type': 'chat_message', 'text': json.dumps(myResponse) } ) return True Check below screenshot for better understanding chat window -
moving tags inside a nav bar
How to move this 'NIHAAL NZ' to the marked position using HTML and css. To the centre of the nav-links. Please try to be elaborate as i;m just a beginner and this is for django websites. Thanks in advance :)[! I found it a bit complicated to move things around and do stuff so please do let me out, this community is so helpful in making progress.Image is given enter image description here]1 HTML CODE: {% load static %} <link rel="stylesheet" href="{% static "portofolio/css/style.css" %}"> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet"> {% block content %} <nav> <div class="logo"> <h4>Nihaal Nz</h4> </div> <ul class="nav-links"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Contact</a></li> </ul> </nav> {% endblock %} CSS CODE: *{ margin: 0; padding: 0; box-sizing: content-box; } p { ; } .nav-link{ font-family: 'Poppins', sans-serif; } nav { display: flex; justify-content: center; align-items: baseline; min-height: 8vh; padding-top: 100px; height: 100px; background-color: black; } .logo { color: rgb(226,226,226); text-transform: uppercase; letter-spacing: 5px; font-size: 20px; font-family: 'Poppins', sans-serif;; } .nav-links { display: flex; justify-content: space-around; width: 30%; } .nav-links li { list-style: none; } .nav-links a { color: rgb(226,226,226); text-decoration: none; letter-spacing: 3px; font-weight: bold; font-size: 14px; font-family: 'Poppins', sans-serif; } -
Source page instead of page and wrong validation
Below is the code to write comments and reply to. I used django 2.2 and jQuery (Ajax part) here. I have a problem with reply to comment forms. When I press "Add answer" (no data in form) the source of the page appears instead of validation. If I add text and press "Add answer" (form with data), an error appears: The view spot.views.SpotDetailView didn't return an HttpResponse object. It returned None instead. Adding comments - works correctly, adds without errors (when data are in form). Validation works (empty form), but error messages also appear on other forms (forms reply to comment). I'm asking for help, thanks. detail_page.html <div class="comment-section"> {% include 'spot/comments.html' %} </div> comments.html <div class="mt-4 mb-4"> {% for comment in object.all_comments %} <div class="card mt-2"> <div class="card-body"> <div class="row"> <div class="col-md-2 col-sm-2"> <img src="https://image.ibb.co/jw55Ex/def_face.jpg" class="img img-rounded img-fluid"/> <p class="text-secondary text-center">{{ comment.date_create }}</p> </div> <div class="col-md-10"> <div class="float-right"> <i class="fas fa-ellipsis-h" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></i> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'spot_comment_update_url' comment.pk %}"><i class="fas fa-edit"></i> Edit</a> <a class="dropdown-item" href="{% url 'spot_comment_delete_url' comment.pk %}"><i class="fas fa-trash-alt"></i> Delete</a> </div> </div> <p><a class="float-left" href="#"><strong>{{ comment.author }}</strong></a></p> <div class="clearfix"></div> <p>{{ comment.text }}</p> </div> </div> {% for reply in comment.replies.all %} <div class="card card-inner … -
Django admin template: what is base_site.html
I am currently customizing the admin templates and this makes me wonders that what is the usage/purpose of base_site.html? I understand that base_site.html extends from base.html but from the original code itself, it only adds HTML content for branding and title blocks. Hence, if I'm overriding the whole base.html, I can just add HTML content for branding and title blocks in base.html and empty the base_site.html. Please correct me if I am wrong. Thank you -
Disable some of tests based on a boolean variable in Django
I have a Django project which has some tests written using Django native test framework. I used selenium for some of these test and I want to be able to disable these test based on boolean defined in settings.py file but I don't know how. Is there a way to do that? This is one of the tests I want to disable: class PublicVoteTests(StaticLiveServerTestCase): def setUp(self): self.question = Question.objects.create(title='sample_title') self.driver = webdriver.Chrome('/usr/bin/chromedriver') self.driver.maximize_window() super().setUp() def tearDown(self): self.driver.quit() return super().tearDown() def test_user_vote_up(self): self.driver.get(self.live_server_url + reverse('action:question-detail', kwargs={'pk': self.question.id})) self.driver.find_element_by_id('q_vote_up').click() self.assertEqual('1', self.driver.find_element_by_id('q_score').text) -
User.is_authonticated returns false in sign in page exceptionally django
There are list of menus in base html, Home Download ... Sign in. The sign in menu should replaced by username if user is signed in. It working except the sign in menu itself. I tried to print the status of user sign in and it never shows that user is signed in. Code of base.html <div class="navbar-nav"> <a class="nav-item nav-link {{ home }} " href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link {{ download }}" href="{% url 'download' %}">Download</a> <a class="nav-item nav-link {{ highScore }}" href="{% url 'highScore' %}">High Score</a> <a class="nav-item nav-link {{ about }}" href="{% url 'about' %}">About</a> {% if user.is_authenticated %} <a class="nav-item nav-link {{ user }}" href="{% url 'user' %}"> Hi {{ user.username }}</a> {% else %} <a class="nav-item nav-link {{ user }}" href="{% url 'user' %}">sign in</a> {% endif %} </div> -
'AbstractBaseUser' is not defined
I am trying to modify the default User model in Models.py by importing the AbstractBaseUser but I am getting the following error: NameError: name 'AbstractBaseUser' is not defined Models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) email = models.EmailField(unique=True, max_length=254) mobile = models.IntegerField(unique=True) verified = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) Also how can I register the url of this app in my main app ? Urls.py urlpatterns = [ path('create-user/', UserCreateAPIView), ] Main Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
Django filter objects by Foreign Key
I have troubles with filtering objects . The objects are displaying in all lists but I have set Foreign key for specific list . Is there any solutions ? models.py class Lists(models.Model): title = models.CharField(max_length=200) class ListsItem(models.Model): date = models.DateTimeField(default=datetime.now,blank=True) title = models.CharField(max_length=200) main_list=models.ForeignKey(Lists, on_delete=models.SET_NULL, null=True) views.py lists = Lists.objects.order_by('date') listitems = ListsItem.objects.filter(main_list__in=lists).order_by('date') template {% if lists %} {% for list in lists %} {{list.title}} {% if listitems %} {% for listitem in listitems %} {{listitem.title_item}} {% endfor %} {% endif %} {% endfor %} {% endif %} -
My Django Orm Query is too slow. How can I index these tables?
I'm developing by Django and Django ORM. My queries are too slow. I wanna upgrade my query, but I don't know how to index. query 1 takes 4 seconds. query 2 takes 7 seconds. models # 40 rows Class Category(models.Model): title = models.CharField(max_length=50, unique=True) # 1,000,000 rows Class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) group = models.ManyToManyField(Group, related_name='group_members', blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) # 10,000,000 rows Class DayLog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='day_log') groups = models.ManyToManyField(Group, related_name='member_day_logs') ms = models.IntegerField(default=0) # 300,000 rows Class Group(models.Model): title = models.CharField(max_length=100, db_index=True) orm 1. query_set = Group.objects.get(id=1).member_day_logs.filter(date='2020-04-29') 2. query_set = Group.objects.get(id=1).member_day_logs.select_related('user__profile').filter(date='2020-04-29').order_by(‘-ms') raw query 1. SELECT * FROM daylog INNER JOIN daylog_groups ON (study_daylog.id = daylog_groups.daylog_id) WHERE (daylog_groups.group_id = 1 AND daylog.date = "2020-04-29") 2. SELECT * FROM daylog INNER JOIN daylog_groups ON (study_daylog.id = daylog_groups.daylog_id) INNER JOIN auth_user ON (daylog.user_id = auth_user.id) LEFT OUTER JOIN profile ON (auth_user.id = profile.user_id) WHERE (daylog_groups.group_id = 1 AND daylog.date = "2020-04-29") ORDER BY daylog.ms DESC explain 1-1 table: day_log_groups, Type: ref, possibleKeys: …., key: …id, key_len: 4, ref: const, rows: 3762, extra: null 1-2 table: day_log, type: eq_ref, possibleKeys:…., key: PRIMARY, key_len: 4, ref: daylog_id, rows: 1, extra: Using where 2-1 table: day_log_groups, type: ref, possibleKeys: … -
Django 3 not compitable for channels
I have a project written in Django 3, now I am trying to implement real-time data visualization with Django channels But Django channels is not compatible with Django 3 Can anyone please help how can i achieve this? -
Convert base64 into zipfile in django
Convert base64 into zipfile in django serializers "image":"File extension “zip” is not allowed. in django -
Postgresql Master-slave replication lagged but pgpool was sending traffic to both db (master n slave)
We do database load balancing using pgpool2 framwork (master + 1 slave). Yesterday I got few database errors on test server saying - 'column X does not exist' Upon debugging we found that master-slave replication has stopped or lagged due to which django migration was done just on master server but not on slave. pgppol was still sending read queries to slave server. How can I avoid such problems or automate such that alarm is raised or notification if anything happen. -
Django-python email form is not forwarding sender's email address via gmail smtp
I am setting email form at my django-python based webpage. I have seen this cool video nicely explaining how setup django and how to incorporate gmail as the smtp server. The form has three fields: Full Name; Email Address; and Message. Everything works fine, but gmail smtp says that I (EMAIL_HOST_USER) am the sender of the message and not the person who fulfilled the form, i.e. I am missing fulfilled email address. From comments under the video, I have found I am not the only one who has this problem and who do not know how to solve it. I have managed only one temporal non-ideal solution to redirect everything from the form (i.e. variables message_name, message_email and message) into the body of the message as follows: send_mail( 'message from ' + message_name, # email_subject 'Full Name: ' + message_name + '; Email Address: ' + message_email + '; Message: ' + message, # message message_email, # from email ['recepient1@example.com', 'recepient2@example.com'], # To Email ) Does somebody know another more elegant solution which would redirect the email address as the real email's sender? Or minimally, please, give me an advice how to print Full Name; Email Address; and Message at … -
Django host: runserver not showing error when it starts with an ip which is not the ip of the host
The following is the ip address of my host which runs the django server ~ # ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 25: eth0@if26: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0 valid_lft forever preferred_lft forever Here the ip addresses are 127.0.0.1 (lo) and 172.17.0.2 (eth0@if26) The netstat shows the routing table ~ # netstat -nr Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 0.0.0.0 172.17.0.1 0.0.0.0 UG 0 0 0 eth0 172.17.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0 ~ # I am planning to start the server on 172.17.0.2 for remote access But before that i want to test to start server on 172.17.0.0 , just want to see what happens $ python runserver 172.17.0.0:8888 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 30, 2020 - 07:10:35 Django version 3.0.5, using settings 'django_project_test.settings' Starting development server at http://172.17.0.0:8888/ Quit the server with CONTROL-C. So the server is starting The netstat shows the port is listening … -
I have Deployed My Django App in apache server . All the static files are getting served properly but its not accepting media files from Form Input
While Submitting a form having media input its showing [Errno 13] Permission denied: '/home/ubuntu/django/media/pictures' I have searched in google but no one told giving permissions for media files , they ever all telling about static files only . Can any one please tell me which permission i have to give to it with chmod no. -
Django - Importing one variable from app1/ models.py to app2/models.py
I'm having difficulties understanding how I can import the "category" variable from Class Questions to my Class post_job. What I want is for me to be possible to add the "category" in the Class post_job. So, when a "job is posted" you can see all the variables including that category. jobs/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class post_job(models.Model): posizione= models.CharField(max_length=20) descrizione= models.TextField(max_length=60) requisiti= models.TextField(max_length=60) nome_azienda= models.CharField(max_length=20, default=' inserisci nome') email_referente= models.CharField(max_length=20, default='inserisci email') def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.posizione quiz/models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) student = models.ManyToManyField(User) class Meta: ordering = ('-catagory',) def __str__(self): return self.question -
I keep getting this error: TypeError: data.map is not a function
i am trying to create a site using django and react, but when i try to view it, i keep getting this error TypeError: data.map is not a function. below is my code, i don't seem to know the problem i am trying to create a site using django and react, but when i try to view it, i keep getting this error TypeError: data.map is not a function. below is my code, i don't seem to know the problem state = { loading: false, error: null, data: [] }; componentDidMount() { this.setState({ loading: true }); axios .get(productListURL) .then(res => { this.setState({ data: res.data, loading: false }); }) .catch(err => { this.setState({ error: err, loading: false }); }); } render() { const { data, error, loading } = this.state; return ( <Container> {error && ( <Message error header="There was some errors with your submission" content={JSON.stringify(error)} /> )} {loading && ( <Segment> <Dimmer active inverted> <Loader inverted>Loading</Loader> </Dimmer> <Image src="/images/wireframe/short-paragraph.png" /> </Segment> )} <Item.Group divided> {data.map(item => { return <Item key={item.id}> <Item.Image src={item.image} /> <Item.Content> <Item.Header as='a'>{item.title}</Item.Header> <Item.Meta> <span className='cinema'>{item.category}</span> </Item.Meta> <Item.Description>{item.description}</Item.Description> </Item.Content> </Item> })} </Item.Group> </Container> ); } } export default ProductList``` -
Donwload MP3 File Django Through Ajax Request
How to download file in django , through ajax call ?. You can assume that , file is ready and you have a file_path) (Note : Don't want to return a file as response, just return a status variable that download is successfull) Please help. -
corseheaders.middleware is not a package
I'm new to django. I'm trying to link my react frontend to my django backend and i need to make the django-cors-headers package work to make axios.post() work. But i keep getting corseheaders.middleware is not a package, although i already installed it using pip and added the config to my settings.py. Any help? This is my settings.py: Django settings for BackEnd project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '----' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'databaseAPI', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware' 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL=True ROOT_URLCONF = 'BackEnd.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
Django Models Not Fetching different URLS
I am trying to create a music website using python django for backend. I need to fetch different spotify urls for different songs and I recommend it using my Django Admin Panel. The problem I am facing is the moment I define url for second song and the consecutive ones my songs fetch the same url I previously defined for first song. In this way, my every song dialog box plays the same song as the first one defined. Here is the model I defined for My Song: Model Image Here are the changes I made in my HTML file to view the model: Dashboard Image And Finally here is the Views I am using in views.py file of app: Views Image Any help would be highly aprreciated. -
Redirect RabbitMQ new messages to WebClients using Django Channels
I have a map application expected to show entities live location on map. The entities send location to Rabbitmq and I'm supposed yo read these locations and redirect them to web clients. I'm going to use Django channels for implementing websochet part. I set up RabbitMQ as Django Channels Channel_layer. My question is how to read data from RabbitMQ (basic_consume) and send it to web client using websocket. I the websocket connet method I call the consume method to start consuming from rabbitMQ: async def connect(self): await self.accept() await self.channel_layer.group_add("gossip", self.channel_name) obj_rabbit_mq = RabbitMQueue() obj_rabbit_mq.consume("my_channel") and this is the consummer part. I can see the body part in my logs but the part that group_send it doesnt work. class RabbitMQueue: def consume(self, queue): print("Consuming {} ...".format(queue)) self.declare_queue(queue) def callback(ch, method, properties, body): print(" Received {}".format(body)) channels_layer = get_channel_layer() print("channels_layer: {}".format(channels_layer)) # async_to_sync(channels_layer.group_send)( channels_layer.group_send( "gossip", { "type": "user.gossip", "event": "New User", "username": body } ) self.channel.basic_consume( queue=queue, on_message_callback=callback, auto_ack=False) print(' [*] Waiting for messages. To exit press CTRL+C') self.channel.start_consuming() -
Uploading multiple images in one field using django rest framework
I am building a website where people can make a post describing something and uploading multiple images to that post as it is getting created. Also even though I want to be able to upload numerous images at the same time, I want users to be able to delete a single image out of the post. My major concern is how my model or view will be set up in order for users to be able to upload the multiple images as planned. I have tried to do a many to many relationships like in my model below but it just doesn't work class Photo(models.Model): ''' photos model ''' url = models.ImageField(blank=True, null=True) class Post(models.Model): ''' post model, allows users to post pictures and describe their feeling at the moment ''' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="post_user") title = models.CharField(max_length=100) description = models.TextField(null=True) photos = models.ManyToManyField(Photo, related_name="assets") likers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_likers") created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.title serializers.py class PhotoSerializer(serializers.ModelSerializer): class Meta: model = Photo fields = ['pk', 'url'] class PostSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field='slug') created_on = serializers.SerializerMethodField(read_only=True) photos = PhotoSerializer() class Meta: model = Post exclude = ['likers', 'updated_on', 'id'] views.py class PostCreateView(generics.CreateAPIView): ''' Create collaborations …