Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Follow Button in Django
I'm new to django and creating a follow button where users can follow a certain profile. When I click 'follow' on the profile, currently I don't get any errors at all. Nothing happens. I don't see anything in my console. There's no error. Am I missing something obvious? No matter what I put in views.py nothing happens. So I don't think it's that. Is it my url? urls.py urlpatterns = [ path("", views.index, name="index"), path("fol/<str:username>", views.fol, name="fol"), path("profile/<str:username>", views.profile, name="profile"), ] models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username class Follow(models.Model): target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') html {% extends "network/layout.html" %} {% load static %} {% block body %} <h3> You are viewing {{ profileuser.username }}'s profile. </h3> <br> <br> <br> <br> {% if user1 != user2 %} <div class="pull-right"> <a href="{% url 'fol' username=profileuser.username %}"></a><input class="btn btn- primary" type="submit" value="Follow"> </div> <br><br> <div class="pull-right"> <input class="btn btn-primary" type="submit" value="Unfollow"> </div> {% endif %} {% for i in page_obj %} <div class='card mb-3' style="max-width: 530px;" id="card-posts"> <div class="row no-gutters"> <div class="col-md-8"> <div … -
Import cannot be resolved pylance error in vscode, have tried a few fixes
I am having trouble using pylint for my Django app. I am receiving a couple of errors and have resolved some using other threads but the main one I am still running into is Import ".forms" could not be resolved. I am hitting this error inside the views.py file when trying to import from forms.py with the following import from .forms import ArtistForm (ArtistForm being a class). I have tried following the below resources but have not been very successful. https://github.com/microsoft/pylance-release/blob/main/TROUBLESHOOTING.md#unresolved-import-warnings This is what I added to my .vscode/settings.json to try and resolve with the above - "python.analysis.extraPaths": ["tunr/", "./tunr/templates/tunr"] I also tried using the .env fix detailed in the below article - https://appdividend.com/2021/03/26/python-unresolved-import/ I am new to coding so I have been having trouble fully understanding how to fix this. Any help is appreciated. Below is my file structure, not the tunr folder is at the root: tunr ├── apps.py ├── models.py ├── templates │ └── tunr │ ├── artist_detail.html │ ├── artist_form.html │ ├── artist_list.html │ ├── base.html │ ├── forms.py │ ├── song_detail.html │ └── song_list.html └── views.py Let me know if any other information will be helpful. -
Django List View Sorting Bulletins
I have a ListView of bulletins I am trying to provide ordering options for. I am using a dropdown to pass a URL parameter called sortBy. I have confirmed via my print statement at the end of def get(self, request): that the order of the queryset changes as expected when different values are passed to sortBy. The problem I am facing is that even though the order of the queryset is changing as expected, this is not being reflected in myTemp.html. The order of the bulletins being displayed are not changing even though the order of the queryset is. What is causing this behavior? Views.py @method_decorator(login_required, name='dispatch') class BulletinList(ListView): model = Bulletin_VW template_name = 'myTemp.html' context_object_name = 'bulletins' additional_context = {} @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_queryset(self): queryset = Bulletin_VW.objects.filter(store_id=self.additional_context['storeID'], entity_id=self.additional_context['entityID']) ordering = self.get_ordering() queryset = queryset.order_by(ordering) return queryset def get_context_data(self, *args, **kwargs): self.object_list = self.get_queryset() context = super(BulletinList, self).get_context_data(*args, **kwargs) context.update(self.additional_context) return context def get_ordering(self): ordering = self.request.GET.get('sortBy', 'Name') sortDict = {'Name': 'author', 'Date-Newest': '-capture_date', 'Date-Oldest': 'capture_date'} ordering = sortDict.get(ordering) return ordering def get(self, request): if not validate_user_session(request.user.id): return redirect('newSession') currentSession = Current_Session_VW.objects.filter(user_id=request.user.id)[0] storeID = currentSession.store_id entityID = currentSession.entity_id entStore = currentSession.entity_store_name balance = get_balance(storeID, … -
Redirect in Django giving 302 response
What I am trying to do is prevent an authenticated user from accessing the signup page. This is what I have written. def validate_request(request): if request.user.is_authenticated and request.user.is_active: print("Condition approved") return redirect("home:home") def signup_view(request): validate_request(request) if request.method == "POST": form = StudentUserSignupForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect("student:email_confirmation") else: redirect("home:home") else: print("Got some other method: ", request.method) form = StudentUserSignupForm() context = { "form": form, } return render(request, "signup_login_form.html", context=context) When I test and create a new user, it gets created successfully and is redirecting fine. However, the new user created is still able to access the signup page. I added some quick print statements at the redirect function call inside validate_request function and the output was <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/"> The URL it was trying to check for is already present and is correct. I replaced the redirect to https://google.com instead of home:home and it still gave the same response. The third thing tried was to redirect as soon as the signup_view function is called. That too was failing with the same response with both internal redirect and redirecting to Google. I have been stuck on this problem for a while. I have gone through … -
FCM django installation error python 3.6.9
Installing fcm-Django on my local was fine, but on the server, I am getting errors. File "/opt/pythonprojects/env/lib/python3.6/site-packages/setuptools/command/build_ext.py", line 203, in build_extension if ext._needs_stub: AttributeError: 'Extension' object has no attribute '_needs_stub' File "/tmp/pip-build-re2xfk5h/grpcio/src/python/grpcio/support.py", line 98, in diagnose_attribute_error "We expect a missing `_needs_stub` attribute from older versions of " commands.CommandError: We expect a missing `_needs_stub` attribute from older versions of setuptools. Consider upgrading setuptools. Command "/opt/pythonprojects/env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-re2xfk5h/grpcio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-ljbtkbh4-record/install-record.txt --single-version-externally-managed --compile --install-headers /opt/pythonprojects/payrink-env/include/site/python3.6/grpcio" failed with error code 1 in /tmp/pip-build-re2xfk5h/grpcio/ Also setuptools is up-to-date on my server which I updated several times. Also tried to install grpcio manually but had no success. Python 3.6.9 -
Django update rows base on order in queryset
I have a simple django model class Item(Model): name = CharField() rank = PositiveIntegerField() created_at = DateField(auto_now_add=True) I want to update the object rank based on their order when sorted by a field (name or created_at) e.g. when ordering by name [("Pen", 0, "2021-05-04"), ("Ball", 0, "2021-05-04")] => [("Pen", 1, "2021-05-04"), (Ball, 0, "2021-05-04")] I already know I can do this using bulk_update but it means I have to fetch the objects in memory items = Items.objects.order_by("name") for i, item in enumerate(items): item.rank = i Item.objects.bulk_update(items, ["rank"]) I was wondering if there is a way to do it with 1 query directly in the database, without having to fetch the data -
For if Loop ManyToMany Field Django
How can I query a manytomanyfield in a Django template? For example, this if statement doesn't work, but this shows what I'd like to do: Model: class Product(models.Model): Category = models.ManyToManyField(Category) Template: {% for p in Product %} {% if p.Category_id == 6 %} {{p.id}} {% endif %} {% endfor %} -
sys.settrace disabling needed or not
The backend REST service I am working is written in python/django and sometimes the server crashes due to one request without reporting the exception i.e. can't even know which line it was where it last reached. The application does not have any function entry/exit logs which could be enabled by environment config so alternative I have come up with was I will enable sys.settrace based on a custom request header. So, I have written something like this in one of the request middleware: def debug_tracer(frame, event, arg = None): code = frame.f_code func_name = code.co_name line_no = frame.f_lineno print(f"A {event} encountered in \ {func_name}() at line number {line_no} ") return debug_tracer if.requests.headers.get("HTTP_TRACEBACK"): sys.settrace(debug_tracer) It behaves like this for a single server deployment: Request at t=1 without traceback header -> Plain request-response logs Request at t=2 with traceback header -> Every line of execution gets into logs along with request-response logs Request at t=3 without traceback header -> Plain request-response logs This is working fine right now, i.e. whenever I pass a header with traceback key, the logs for that particular request contain the details calls/returns/lines. But I am not able to understand that without doing sys.settrace(None) i.e. actively disabling the … -
How to setup alias in Nginx
I deployed a django application using Digital ocean plateform. When nginx was serving static files through roots everything worked fine. But the moment installed boto3 and Django_storage and turned to alias nginx stopped serving the static files. I saw that similar question was asked but I still don't understand why the static files are not been served. After running python manage.py collectstatic the staticfiles appeared in the folder in digital ocean space but the staticfiles are not being served on the browser. My project structure is as follows: $myprojectdir/ myproject/ settings.py static/ manage.py ... settings.py AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '*** AWS_S3_ENDPOINT_URL = '***' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = '***' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' sudo vim /etc/nginx/sites-available/myproject server { server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/sammy/myprojectdir/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.flolog.co/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.flolog.co/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host … -
count duplicate words in arrayField of postgres django
In my django's array field Is there any way I can count how many duplicate elements there are in the query_set query? For example, I have tags ["A", "B", "C"] Each object you query in the list will know how many characters it matches Object 1 with tags ["A", "B", "F"] has the same 2 Object 2 with tags ["H", "S", "B"] has the same 1enter image description here -
Setup user role read/edit project by project, Django ORM
I am trying to implement a relationship between three tables; User Project and Permissions I already have a ManyToMany relationship between User and Project class CustomUser(AbstractUser): username = models.CharField(unique=True, max_length=20, null=False, blank=False) // etc... class Project(models.Model): user = models.ManyToManyField(CustomUser, related_name="projects") Now I am trying to add the Permission Table. So that User can take different roles on different project. class Permissions(models.Model): can_read = models.BooleanField(default=True) can_read_and_edit = models.BooleanField(default=False) // etc... What is the best approach on this situation. Should I Add Permission table into manytomany relation as a third table? Or is there a better way to achieve this -
Django recursive relationship in many-to-one and many-to-many
I'm reading Django documentation and currently trying to understand the Django models recursive relationship in many-to-many and many-to-one and I still don't get it. Can anybody help to explain in what situation we need to use recursive relationship? And how will the recursive many-to-one be different from the recursive many-to-many? Will be great if perhaps in an example. Thank you in advance. -
How to use string values of a variable as a django model queries?
I have some Model Fields those are related to User model by many to many relationship class SocialPost(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, related_name='users_post' ) privacy=models.CharField(max_length=100,blank=True, null= True) post_text=models.TextField(blank=True, null= True) location=models.CharField(max_length=100,blank=True, null= True) feeling_or_activity=models.CharField(max_length=100,blank=True, null= True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(blank=True,null=True) category=models.CharField(max_length=100,blank=True, null= True) tags=models.ManyToManyField(User, related_name='taglist',blank=True) views = models.ManyToManyField(User, related_name='post_views',blank=True) likes = models.ManyToManyField(User,related_name='post_likes',blank=True) love=models.ManyToManyField(User,related_name='post_loves',blank=True) angry=models.ManyToManyField(User,related_name='post_angries',blank=True) haha=models.ManyToManyField(User,related_name='post_hahas',blank=True) sad=models.ManyToManyField(User,related_name='post_sads',blank=True) care=models.ManyToManyField(User,related_name='post_cares',blank=True) senti=models.ManyToManyField(User,related_name='post_senties',blank=True) wow=models.ManyToManyField(User,related_name='post_wows',blank=True) I will get values like reaction='wow' through API call. i want to call like variable=object.reaction.filter() Which will be always call by reaction variables value. as example if reaction='like' it will call variable=object.like.all() and if reaction='sad' it will call variable=object.sad.all() i don't know how can i do this! can anyone help me in this problem? -
Javascript/Jquery: How we can use loading spinner for download some report from our web-page
I'm Just stuck with some problem which is "Generate Report". It actually download the report and it takes time to generate and download the report. So I just want to use loading spinner for that download file. I'm new to understand the concept of Javascript/Jquery. In this logic, I haven't used any ajax request. Also I've 2 files like i.e. .html file and .js, Please suggest me how to solve this logic. I've explored everywhere, couldn't find anything. -
How to automatically set the thread instead of user having to set it in django
I am trying to create a discussion forum website with django. Everything is working, but I want to change one thing and I have no idea how to. In the website users can create threads and posts inside those threads. When a thread is created there is a button in that thread that says add a post in this thread. Then it will take them to a form. Right now, if the form were to work they would have to select from a dropdown menu which thread they wanted to add a post to. I want the thread to be the thread that the button they clicked was inside of. models.py: class Thread(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) description = models.CharField(max_length=1000) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('thread-view', kwargs={'pk': self.pk}) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('post-view', kwargs={'pk': self.pk}) views.py: def homeView(request): context = { 'threads': Thread.objects.all().order_by('-created_at'), 'posts': Post.objects.all().order_by('-created_at') } return render(request, 'forum/home.html', context) class ThreadCreateView(CreateView): model = Thread fields = ['title', 'description'] # Right now I also have to add in 'thread' as … -
Reverse for with no arguments not found for URL
I am attempting to create a view that allows users to delete a build log. On the view that shows the delete button with a link to the delete page I am getting the error Reverse for 'build-log-delete' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/build\\-log/(?P<pkz>[0-9]+)/delete$'] If I understand this error correctly its because I am not passing paramaters in the url. <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> However I do not understand why I need to pass parameters in the URL as I am not passing any new values into the URL and if so what parameters I would pass. Do I have to re pass the previous two? urls path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete', views.BuildLogDelete, name='build-log-delete') #error views def BuildLogDisplay(request, pk, pkz ): post = BuildLog.objects.filter(post_id=pk) log = BuildLog.objects.get(pk=pkz) context = { 'post':post, 'log':log } return render(request, 'blog/buildlog.html', context) def BuildLogDelete(request): context = { } return render(request, 'blog/BuildLogDelete.html', context) full template <div class="row"> <article class="cars-article"> <div class="flex"> <img class="rounded-circle article-img" src="{{ log.author.profile.image.url }}" /> <div> <a class="article-title">{{ log.title }}</a> </div> </div> <br> <div> {% if log.author == user %} <a class="update-btn" href=""> Update</a> <a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a> {% endif %} </div> <hr class="solid"> <p class="article-content">{{ log.content … -
Formset is not giving me 3 of the form by default and got KeyError when saving
Hi i have the following error while using formset. Exception Type: KeyError Exception Value: 'module' This error happen when i try to press save on the add page. Currently in my webpage, theres only 1 formset. I read online by default its 3 but even after i add extra=3. Its still 1. Can anyone help me? Here are my codes: views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) #di_form= DeviceInterfaceForm(request.POST) di_formset = modelformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), extra = 3) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device # If you did not render the hostname for the device detail, set it from the value of new device deviceD.hostname = new_device.hostname deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) deviceI.I2DKEY=new_device deviceI.save() new_device=Device.objects.all() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) else: device_frm = DeviceForm() dd_form = DeviceDetailForm() di_form = DeviceInterfaceForm() return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) … -
bulk_create always causes primary key error (sql server)
Using Django 3.2.6, DB - SQL Server I'm trying to use bulk_create to create a set of rows in my database. In my view, I create a list of Model objects like this and use bulk_create asset_map_list = [] for row in data_list: asset = Asset(asset_type=AssetType.objects.get(name=asset_type_name), asset_name=row['asset_name'], display_name=row['display_name']) asset_list.append(asset) Asset.objects.bulk_create(asset_list) However it keeps throwing a Primary key error django.db.utils.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Violation of PRIMARY KEY constraint 'PK__mm_asset__xxxxxx' My Asset and Asset Type models look like this: class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) I tried setting ignore_conflicts=True but SQL Server doesn't support that. I tried doing df.to_sql() but it gets complicated because of the foreign key (as you can see -- the user inputs asset type NAME but in my asset DB I'm storing asset type ID ) Can someone please help me solve this bulk_create issue or point me to a better alternative? Thanks -
How to deal with empty foreign keys in a for loop within django View
I have a model which acts a as schedule where there are multiple FK relationships to the same user table. All of these fields can be blank/null. The issue is, when i do a for loop, i am trying to match the users based on when they appear on a certain shift, then add a +1 to a counter to get the total shifts for that user. The model looks like this: class WeekdayAssignment(models.Model): """Model definition for WeekdayAssignment.""" start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) triage_emea_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_emea_1", blank=True, null=True) triage_nam_1 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_1", blank=True, null=True) triage_nam_2 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_2", blank=True, null=True) triage_nam_3 = models.ForeignKey(TeamMember, on_delete=models.DO_NOTHING, related_name="triage_nam_3", blank=True, null=True) ... As you can see i have 4 triage shifts and the same user can work any of those shifts. I want to do a for loop to count how many times a user is on a shift in any one of those fields. Without getting into all the details of what I am doing, i will keep it simple as the error happens right away. Views.py def someview(request): shift_users = TeamMember.objects.all() weekday_shifts = WeekdayAssignment.objects.all() for t in shift_users: for ws in weekday_shifts: print(ws.triage_nam_3) As long … -
How to submit information using Django?
I have the following form in a modal and I want to save the information in the DB but it does not happen. but if I manage to remove an attribute from the submit button if I save it but the button validations and actions disappear. <button type="submit" class="btn btn-primary" data-kt-account-modal-action="submit"> replacing with this if it works and saves but validations no longer work. <button type="submit" class="btn btn-primary"> -
Django - Populate field based on user selection from dropdown
I want to have the following: User selects a Location ID from a dropdown list and then the next field shows the Location description (name_county_postcode) associated with that ID automatically. I have two models set up: class UkTowns(models.Model): id = models.IntegerField(primary_key=True) locationid = models.CharField(max_length=8, blank=True, null=True) name_county_postcode = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.locationid class Project(models.Model): projectid = models.IntegerField('ProjectID', db_column='ProjectID', primary_key=True) locationid = models.ForeignKey(UkTowns, models.DO_NOTHING, verbose_name="LocationID", db_column='LocationID', max_length=50) project_name = models.CharField('Project Name', db_column='Project_Name', max_length=300) author = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, db_column='Author_id') def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) The following views: class PostCreateView(LoginRequiredMixin, CreateView): model = Project fields = ['projectid','project_name','locationid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Project fields = ['projectid','project_name','locationid'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): Project = self.get_object() if self.request.user == Project.author: return True return False And the following html page: {% extends "costcapture/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Project</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> {% endblock content %} Currently the form works with the fields from PostCreateView and PostUpdateView (it shows more than what I've included … -
Why is django filling spaces to the max length of the char field?
I have some char fields in django that look like this: attrunit = models.CharField(db_column='AttributeUnit', max_length=64, blank=True, null=True) To my understanding, the blank option allows users to write empty form values, and null means the entry does not need to be populated at all in the database. However, whenever I write to any of my CharFields, django seems to backfill spaces up to the max length of the field. For reference, I routed all of my write-models into a MSSQL server database (not the default SQLLite db that django builds). I'm at a loss as to where these spaces are coming from and I do not want to have to strip the values every time I read them out from the db. -
Django - build HTML table in template using multiple models - one model for columns, one for rows
I'm quite sure this has been answered but I'm not really sure what keywords I need to use to find the answer. I have a simple model that has a foreign key relationship with the built-in User model. There's also a UniqueConstraint to prevent a user from having more than one pick per game. class PickModel(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) game_number = models.IntegerField(blank=False, null=False) class Meta: constraints = [ models.UniqueConstraint(fields=['user','game_number'], name='One user pick per game') ] I need to build an HTML table that summarizes this info. Columns of the table should be users and rows should be the picks. How should I structure the data in my view so that I can loop through it in the template and make sure that a user's pick falls in the correct column? I basically need to be able to loop through both users and picks at the same time. Do I need to do a join on these tables in my view or is there a way to handle this only using template tags/logic? -
Django tests. Equvalent to request.COOKIE
I read a lot on Google and stack, but couldn't find the answer. I got some piece of code in my view: try: cart = json.loads(request.COOKIES['cart'])['products'] except: cart = {} I'm getting data from created cookie (for example name: cart, value: {"products":{"1":{"quantity":1}}}). The problem is: how to test that view by TestCase in Django? For example I tried to use: self.client.cookies["cart"] = {"products":{"1":{"quantity":1}}} But client.cookies is not equal to request.COOKIES. My test everytime fails. Should I put more code? PS. My view works fine, i got problems just with testing. -
How can I spawn a listener from Django?
I want to be able to start a Twitter stream listener upon a request on the django project. For example: user creates a Tracker object (keywords: apple, microsoft). Then calls the /trackers/1/start endpoint and the view starts a thread/coroutine to listen Twitter stream for these keywords. Whenever a tweet appears in the stream, it creates a celery task to save the tweet. Of course, it should be non-blocking. So: should I create new threads per tracker (twitter listener)? should I use async def views? I could create sync or async functions for the tweepy listener/stream. Currently I'm having RuntimeError: You cannot use ATOMIC_REQUESTS with async views. when I do this. By the way, I plan to deploy on Heroku but I can choose VPS if that's not feasible for this problem.